//
//  CBJStatuesListViewModel.swift
//  Weibo
//
//  Created by 崔健 on 16/5/25.
//  Copyright © 2016年 cbj. All rights reserved.
//

import UIKit

class CBJStatuesListViewModel: NSObject {

    lazy var statuesList : [CBJStatuesViewModel] = [CBJStatuesViewModel]()

    
    func loadStatusData(isPulling: Bool,finished: (isSuccess: Bool)->()){

        let token = CBJUserAccountViewModel.sharedAccountViewModel.userAccount?.access_token
        var maxID : Int64 = 0
        var sinceID :Int64 = 0
        if isPulling { // 是下拉加载吗
            
            maxID = statuesList.last?.statues?.id ?? 0
        }else{
        
            sinceID = statuesList.first?.statues?.id ?? 0
        }
        
        
        var paramaters = ["access_token" : token as! AnyObject]
        if sinceID > 0 {
            paramaters["since_id"] = "\(sinceID)"
        }
        
        if maxID > 0 {
            
            paramaters["max_id"] = "\(maxID - 1)"
        }
        
        CBJNetworkTools.sharedInstance.request(.GET, urlString: API.loadHomeData, parameters: paramaters) { (responseObject, error) in
            
            if error != nil{
                
                finished(isSuccess: false)
                return
            }
            
            
            guard let array = responseObject!["statuses"] as? [[String:AnyObject]] else{
                
                return
            }
            
            var tempArray = [CBJStatuesViewModel]()
            for item in array{
                
                
                tempArray.append(CBJStatuesViewModel(statues: CBJStatues(dict: item)))
            }
            
            if isPulling{
            
                self.statuesList = self.statuesList + tempArray
                
            }else{
            
                self.statuesList = tempArray + self.statuesList

            }
            
            
            finished(isSuccess: true)
            
        }
    }
    
    
    
}
